//
//  ViewController.m
//  KKRSA
//
//  Created by liaozhenming on 16/7/13.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

#import "ViewController.h"

#import "KKRSAEncryptor.h"

#include <rsa.h>

#define RSA_Public_key         @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxuWhp6EgQfrrSBtxlBwbU35lhjC67X0Y1KrhqolIfYo3/yWV1eryYVUhk5xeHsbKg9RHD9TpIZRUWIW5a8MrMBcgr1A/dgIHi2EM28drH4JRTmkTLVHReggFbb046k0ISpLW3XVW0jHB3/z3S1c/NT9V63SQK6WJ65/YP5xISNQIDAQAB"

#define RSA_Privite_key        @"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALG5aGnoSBB+utIG3GUHBtTfmWGMLrtfRjUquGqiUh9ijf/JZXV6vJhVSGTnF4exsqD1EcP1OkhlFRYhblrwyswFyCvUD92AgeLYQzbx2sfglFOaRMtUdF6CAVtvTjqTQhKktbddVbSMcHf/PdLVz81P1XrdJArpYnrn9g/nEhI1AgMBAAECgYBEbsMAvLs69sFS6+djU1BTGYIC6Kp55ZawFDIMhVIf2aAZ1N+nW8pQ0c3dZIpP6qGAjrz3em6lv55d9iN7Cura/g57Rk4S3SRo5u4hWUd16NeIVP+HfreKIgZ6jwKQTfXt2KzDuIAHudvwT2UJBePgIIDQoKMEq4khtFiRGS1UgQJBAN/KpSOiRiGup8h/Iqespwfxyrqn5/4iyw1tpJCWzHddP7nJGpYmOL+ELWs/pReYclAOqH9ZIzOT2K8ZLt6yBOECQQDLTXZowK8wFgMudAE5TStC/zl3TAKMu/Gu5wlXSMoa+nwSy/FSIQZyypGeHR2X8QhbZ1Qz+uBCJm7gEGOWMWPVAkEAp5ajsFm3V0XqE/VRSGu88fAaN0nCK8h2cunm0Ph8ye6k6EY3iLW6zYD4WlZhFZhuEpHHkQZ5nAhdvlKHjPGXQQJAYOtF1rx9B/SGgb/F0ZZrWF4p/ChdUtBKcHIt7tGBoAjn22IkYl3iIBlYAEOrFwNOU5zX9IvWG1MNKn5Fq5VSHQJBAJG5xSY0IKzXWDsGnPIa9XlSTv1zl7RCGNDo7O1zh+5J/kjDpU9M2fIXEtzvGYHiOffz9FBh5ka69JJNFWoWAiw="

@interface ViewController ()

@end


static NSString * RSA_Mod = @"BEBAC6BC9B95D0B25B032760D33D583AF3BC28ECF05A8F46D9D07086C693EBFC76DDD80B8A915EC6C45D1737FAC0F72F229AC6A3582875793965B46A9283715026745787ACD1D7BA12F915FE079A9EA8D0899EB27CB1BD92BF49807817C799C5BF5B24986014CB2BD25B5C4102CB278DF21C585C41613454386BAF1C29EE7C43";

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
//    NSString *encryptResult = [KKRSAEncryptor kk_encryptString: @"123456" publicKey: RSA_Public_key];
//    NSString *decryptResult = [KKRSAEncryptor kk_decryptString: encryptResult privateKey: RSA_Privite_key];
//    NSLog(@"decryptResult = %@", decryptResult);

    NSLog(@"decryptResult3 = %@", [self setPublicKey: [@"123456" UTF8String] Mod: [@"AF0625D78FB8B2F1A87B1DFDE4CC829583B2092AFED4AB20383CD27777E462001CCFB85B498518231614DCE6A901740F69455E16BD1F924B7292D6E5AE0C600200FD400DFCC4296F103D1EF9533BD472C9FE7CC2977EC9A6284CD9A31261AE96C22E065A8ABA6E3405E7BE53C09802F765EC56E1914A4735272E7139AA66047F" UTF8String] Exp: [@"010001" UTF8String]]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *)setPublicKey:(const char *)data Mod:(const char *)mod Exp:(const char *)exp
{
    RSA * pubkey = RSA_new();
    
    BIGNUM * bnmod = BN_new();
    BIGNUM * bnexp = BN_new();
    
    BN_hex2bn(&bnmod, (const char *) mod);
    BN_hex2bn(&bnexp, exp);
    
    pubkey->n = bnmod;
    pubkey->e = bnexp;
    
    int nLen = RSA_size(pubkey);
    char *crip = (char *)malloc(sizeof(char*)*nLen+1);
    
    //RSA_print_fp(stdout,pubkey,10);
    
    int nLen1 = RSA_public_encrypt(strlen((const char *) data), (const unsigned char *) data, (unsigned char *) crip, pubkey, RSA_PKCS1_PADDING );
    //NSLog(@"len size : %d",nLen1);
    if (nLen1 <= 0)
    {
        NSLog(@"erro encrypt");
    }
    else
    {
        
        NSLog(@"SUC encrypt");
        
    }
    
    free(crip);
    RSA_free(pubkey);
    
    NSData *resData = [NSData dataWithBytes:crip length:nLen];
    return [self hex:resData useLower:NO];
}

- (NSString *)hex: (NSData *)data useLower: (bool)isOutputLower
{
    static const char HexEncodeCharsLower[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    static const char HexEncodeChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    char *resultData;
    // malloc result data
    resultData = malloc([data length] * 2 +1);
    // convert imgData(NSData) to char[]
    unsigned char *sourceData = ((unsigned char *)[data bytes]);
    uint length = [data length];
    
    if (isOutputLower) {
        for (uint index = 0; index < length; index++) {
            // set result data
            resultData[index * 2] = HexEncodeCharsLower[(sourceData[index] >> 4)];
            resultData[index * 2 + 1] = HexEncodeCharsLower[(sourceData[index] % 0x10)];
        }
    }
    else {
        for (uint index = 0; index < length; index++) {
            // set result data
            resultData[index * 2] = HexEncodeChars[(sourceData[index] >> 4)];
            resultData[index * 2 + 1] = HexEncodeChars[(sourceData[index] % 0x10)];
        }
    }
    resultData[[data length] * 2] = 0;
    
    // convert result(char[]) to NSString
    NSString *result = [NSString stringWithCString:resultData encoding:NSASCIIStringEncoding];
    sourceData = nil;
    free(resultData);
    
    return result;
}
@end
